package com.hsq.androidproject.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.lenovo.androidproject3.R;
import com.hsq.androidproject.entity.StarDynamicTmp;
import com.hsq.androidproject.entity.VideoInfo;
import com.hsq.androidproject.ui.IjkFullscreenActivity;
import com.hsq.androidproject.utils.OkHttpClientManager;
import com.hsq.androidproject.utils.SDUtils;
import com.hsq.androidproject.utils.glide.GlideRoundTransform;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import static java.net.HttpURLConnection.HTTP_OK;


/**
 * Created by hsq on 2016/11/22.
 */

public class MyGridViewStarDTAdapter extends BaseAdapter {        ////明星排行榜
    private List<StarDynamicTmp> mData;
    private Context context;
    public MyGridViewStarDTAdapter(List<StarDynamicTmp> mData, Context context) {
        this.mData = mData;
        this.context = context;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.layout_griddtview, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.dt_image);
            viewHolder.tv_title = (TextView) convertView.findViewById(R.id.dt_title);
            viewHolder.ll_click = (LinearLayout) convertView.findViewById(R.id.ll_click);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final StarDynamicTmp hotStarsBean = mData.get(position);
        String thumb = hotStarsBean.getThumb();
        Glide.with(context)
                .load(thumb)
                .transform(new GlideRoundTransform(context, 3))//圆角
                .into(viewHolder.iv_image);
        String title = hotStarsBean.getTitle();
        viewHolder.tv_title.setText(title);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url=new URL("http://api.hanju.koudaibaobao.com/api/star/vdanmu?vid="+hotStarsBean.getVid()+"&fromAxis=0&offset=0&toAxis=60000");
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);
                    int code = connection.getResponseCode();
                    if (code== HTTP_OK) {
                        InputStream inputStream = connection.getInputStream();
                        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
                        int len=0;
                        byte[] bytes=new byte[1024];
                        while ((len = inputStream.read(bytes)) != -1) {
                            outputStream.write(bytes,0,len);
                        }
                        byte[] data = outputStream.toByteArray();
                        SDUtils.saveToSd(data,"data",hotStarsBean.getVid()+".xml");
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        final String url1 = hotStarsBean.getPage();//path
        String aid = url1.substring(32);
        final String path = "http://api.bilibili.com/playurl?platform=html5&quality=1&vtype=mp4hd&type=jsonp&aid=" + aid + "&page=1&token=d41d8cd98f00b204e9800998ecf8427e&callback=jsonp_" + System.currentTimeMillis() + "000";
              /*  Toast.makeText(context, "" + url, Toast.LENGTH_SHORT).show();       /////》？？？？？？？*/

        viewHolder.ll_click.setOnClickListener(new View.OnClickListener() {     ////    点击LinearLayout，跳转页面播放视屏
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                OkHttpClientManager.getAsyn(path, new OkHttpClientManager.ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }
                    @Override
                    public void onResponse(String response) throws IOException {
                        int i = response.indexOf(")");
                        String substring = response.substring(23,i);
                        VideoInfo info = new Gson().fromJson(substring, VideoInfo.class);
                        Intent intent = new Intent(context, IjkFullscreenActivity.class);
                        intent.putExtra("path",info.getDurl().get(0).getUrl());
                        intent.putExtra("img",hotStarsBean.getThumb());
                        intent.putExtra("title",hotStarsBean.getTitle());
                        intent.putExtra("danmu","http://api.hanju.koudaibaobao.com/api/star/vdanmu?vid="+hotStarsBean.getVid()+"&fromAxis=0&offset=0&toAxis=60000");
                        intent.putExtra("id",hotStarsBean.getVid());
                        Log.d("TAG", "run: "+"http://api.hanju.koudaibaobao.com/api/star/vdanmu?vid="+hotStarsBean.getVid()+"&fromAxis=0&offset=0&toAxis=60000");
                        context.startActivity(intent);
                    }
                });
            }
        });
        return convertView;
    }


    class ViewHolder {
        private TextView tv_title;
        private ImageView iv_image;
        private LinearLayout ll_click;
    }
}


